package com.sky.edumanageapi.pay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.internal.util.AlipaySignature;
import com.sky.edumanageapi.order.pojo.entity.Order;
import com.sky.edumanageapi.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("/alipay")
public class AliPayController {

    @Autowired
    private AliPayConfig alipayConfig;

    @Autowired
    private OrderService orderService;
    @GetMapping("/pay")
    @ResponseBody
    public String pay(@RequestParam Integer orderId, HttpServletRequest request) {
        Order order = orderService.selectByOrderId(orderId);

        // 创建AlipayClient实例
        AlipayClient alipayClient = new DefaultAlipayClient(
                "https://openapi.alipay.com/gateway.do",
                alipayConfig.getAppId(),
                alipayConfig.getAppPrivateKey(),
                "json",
                "UTF-8",
                alipayConfig.getAlipatyPublicKey(),
                "RSA2"
        );

        // 创建API对应的request
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
      // 这里使用notifyUrl作为returnUrl，可以根据实际需求调整
        alipayRequest.setNotifyUrl(alipayConfig.getNotifyUrl());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_No", order.getOrderId());
        jsonObject.put("total_amount",order.getPrice());
        jsonObject.put("subject",order.getCourseId());
        jsonObject.put("product_code", "FAST_INSTANT_TRADE_PAY");
        alipayRequest.setBizContent(jsonObject.toString());
        //执行请求,拿到响应结果,返回给浏览器
        String form = "";
        try {
            form=alipayClient.pageExecute(alipayRequest).getBody();
            System.out.println("Form content: " + form); // 输出表单内容

            return form;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "支付请求失败";
        }



    }

    @PostMapping("/notify")
    @ResponseBody
    public String notify(HttpServletRequest request) {
        // 获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = false; // 调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipatyPublicKey(), "UTF-8", "RSA2");
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        // ——请在这里编写您的程序（以下代码仅作参考）——
        if (signVerified) {
            // 验证成功
            // 请务必校验通知中的out_trade_no（商户订单号）是否为商户系统中创建的订单号，并且验证total_amount（订单金额）是否与商户系统中的订单金额一致。
            // 根据业务逻辑处理订单状态更新等操作
            return "success";
        } else {
            // 验证失败
            return "failure";
        }
    }
}
